package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.zzyl.common.utils.*;
import com.zzyl.common.utils.spring.SpringUtils;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.vo.health.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

import static com.zzyl.common.constant.Constants.HEALTH_REPORT_PROMPT_TEMPLATE;

/**
 * 健康评估Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-22
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private BaiduQianfanUtils baiduQianfanUtils;

    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 上传体检报告
     *
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file, String idCardNo) throws Exception {
        // 1. 将报告存储到Oss
        String url = aliyunOSSUtil.upload(file.getInputStream(), file.getOriginalFilename());

        //  2.读取pdf报告
        String content = PDFUtil.pdfToString(file.getInputStream());

        // 3.将读取的内容缓存
        redisTemplate.opsForHash().put("lealthReport", idCardNo, content);

        return url;
    }

    /**
     * 新增健康评估
     *
     * @param
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto healthAssessmentDto) {
        // 1.设计Prompt
        String prompt = getPrompt(healthAssessmentDto.getIdCard());

        // 2.根据Prompt Ai评测,结果为json格式
        String aiAnswer = baiduQianfanUtils.qianfanInvoker(prompt);

        // 3.将评测结果保存到数据库
        HealthReportVo aiReport = JSONUtil.toBean(aiAnswer, HealthReportVo.class);
        Long id = saveHealthAssessment(aiReport, healthAssessmentDto);
        return id;
    }



    /**
     * 组装提示词
     * @param idCard
     * @return
     */
    private String getPrompt(String idCard) {
        String content = (String) redisTemplate.opsForHash().get("lealthReport", idCard);
        redisTemplate.opsForHash().delete("lealthReport", idCard);
        String prompt = StringUtils.format(HEALTH_REPORT_PROMPT_TEMPLATE,content);
        return prompt;
    }

    /**
     * 将 AI 评测报告存入数据库
     * @param aiReport
     * @param healthAssessmentDto
     * @return
     */
    private Long saveHealthAssessment(HealthReportVo aiReport, HealthAssessmentDto healthAssessmentDto) {
        HealthAssessment healthAssessment = new HealthAssessment();
        // 1.设置老人姓名
        healthAssessment.setElderName(healthAssessmentDto.getElderName());

        // 2.设置身份证号
        healthAssessment.setIdCard(healthAssessmentDto.getIdCard());

        // 3.设置出生日期
        LocalDateTime birthDateByIdCard = IDCardUtils.getBirthDateByIdCard(healthAssessmentDto.getIdCard());
        healthAssessment.setBirthDate(birthDateByIdCard);

        // 4.设置年龄
        healthAssessment.setAge(IDCardUtils.getAgeByIdCard(healthAssessmentDto.getIdCard()));

        // 5.设置性别
        healthAssessment.setGender(IDCardUtils.getGenderFromIdCard(healthAssessmentDto.getIdCard()));

        // 6.设置健康评分
        healthAssessment.setHealthScore(String.valueOf(aiReport.getHealthAssessment().getHealthIndex()));

        // 7.设置危险等级
        healthAssessment.setRiskLevel(aiReport.getHealthAssessment().getRiskLevel());

        // 8.设置是否建议入住
        healthAssessment.setSuggestionForAdmission(extracted(aiReport));

        // 9.推荐护理等级
        String content = getRecommendedNursingLevel(aiReport);
        healthAssessment.setNursingLevelName(content);

        // 10.入住情况
        healthAssessment.setAdmissionStatus(1);

        // 11.总检日期
        healthAssessment.setTotalCheckDate(aiReport.getTotalCheckDate());

        // 12.体检机构
        healthAssessment.setPhysicalExamInstitution(healthAssessmentDto.getPhysicalExamInstitution());

        // 13.体检报告URL链接
        healthAssessment.setPhysicalReportUrl(healthAssessmentDto.getPhysicalReportUrl());

        // 14.评估时间
        healthAssessment.setAssessmentTime(LocalDateTime.now());

        // 15.报告总结
        healthAssessment.setReportSummary(aiReport.getSummarize());

        // 16.疾病风险
        healthAssessment.setDiseaseRisk(JSONUtil.toJsonStr(aiReport.getRiskDistribution()));

        // 17.异常分析
        healthAssessment.setAbnormalAnalysis(JSONUtil.toJsonStr(aiReport.getAbnormalData()));

        // 18.健康系统分值
        healthAssessment.setSystemScore(JSONUtil.toJsonStr(aiReport.getSystemScore()));

        save(healthAssessment);
        return healthAssessment.getId();
    }

    private Integer extracted(HealthReportVo aiReport) {
        double healthIndex = aiReport.getHealthAssessment().getHealthIndex();
        if (healthIndex > 100 || healthIndex < 0) {
            throw new IllegalArgumentException("健康评分异常");
        }
        return healthIndex >= 90 ? 1 : 0;
    }




    /**
     * 根据健康评分推荐护理等级
     * @param aiReport
     * @return
     */
    private String getRecommendedNursingLevel(HealthReportVo aiReport) {
        double healthIndex = aiReport.getHealthAssessment().getHealthIndex();
        if (healthIndex > 100 || healthIndex < 0) {
            throw new IllegalArgumentException("健康评分异常");
        }
        if (healthIndex >= 90) {
            return "特级护理";
        } else if (healthIndex >= 80) {
            return "一级护理";
        } else if (healthIndex >= 70) {
            return "二级护理";
        } else if (healthIndex >= 60) {
            return "三级护理";
        }else {
            return "四级护理";
        }
    }
}
